package com.funtonow.jqdk.fkcs.ui;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.funtonow.jqdk.R;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.fkcs.ui.fragment.FkHomeFragment;
import com.funtonow.jqdk.fkcs.ui.fragment.MyFragment;
import com.funtonow.jqdk.utils.LogUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import butterknife.BindView;

/**
 * @author Jiajien
 * @date 2019/7/12
 */
public class FkMainActivity extends BaseActivity {

    @BindView(R.id.navigation)
    BottomNavigationView bottomNavigationView;

    private Fragment[] fragments = new Fragment[2];
    private int lastFragment;//用于记录上个选择的Fragment

    @Override
    public int getLayoutRes() {
        return R.layout.activity_fk_home;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initFragment();
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.navigation_home:
                        if (lastFragment != 0) {
                            switchFragment(lastFragment, 0);
                            lastFragment = 0;
                        }
                        return true;
                    case R.id.navigation_notifications:
                        if (lastFragment != 1) {
                            switchFragment(lastFragment, 1);
                            lastFragment = 1;
                        }
                        return true;
                    default:
                        return false;
                }
            }
        });
    }

    private void initFragment() {
        FkHomeFragment homeFragment = FkHomeFragment.newInstance();
        MyFragment myFragment = MyFragment.newInstance();
        fragments = new Fragment[]{homeFragment, myFragment};
        lastFragment = 0;
        getSupportFragmentManager().beginTransaction().replace(R.id.fl_content_layout, homeFragment).show(homeFragment).commit();
    }


    private void switchFragment(int lastFragment, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(fragments[lastFragment]);//隐藏上个Fragment
        if (!fragments[index].isAdded()) {
            transaction.add(R.id.fl_content_layout, fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }


}
